module(...,package.seeall)

require"sys"

local inf = {}

local function proc(msg)
	
	if msg then
		print("chg msg.charger",msg.charger,msg.state,msg.level,msg.voltage)
		setcharger(msg.charger)
		setstate(msg.state)
		inf.lev = msg.level
		inf.vol = msg.voltage		
		
		if inf.lev == 0 and not inf.chg then
			if not inf.poweroffing then
				inf.poweroffing = true
				sys.timer_start(rtos.poweroff,30000,"chg")
			end
		elseif inf.poweroffing then
			sys.timer_stop(rtos.poweroff,"chg")
			inf.poweroffing = false
		end
		
		sys.dispatch("CHARGER_STATUS_IND",msg.charger)
		if inf.lev <= inf.warnlev and not getcharger() then
			sys.dispatch("BAT_LOW_IND",inf.vol)
		end
		print("chg proc",inf.chg,inf.state,inf.lev,inf.vol)
	end
end

local function init()
	inf.vol = 0
	inf.lev = 0
	inf.chg = false
	inf.state = 0
	inf.poweroffing = false
	inf.warnlev = 20
	
	local para = {}	
	para.battFullLevel = 4200
	para.poweroffLevel = 3400
	pmd.init(para)
end

function getcharger()
	return inf.chg
end

function setcharger(f)
	if inf.chg ~= f then
		inf.chg = f
		sys.dispatch("DEV_CHG_IND")
	end
end

function getvolt()
	return inf.vol
end

function getlev()
	if inf.lev == 255 then inf.lev = 95 end
	return inf.lev
end

function getstate()
	return inf.state == 1
end

function setstate(f)
	if inf.state ~= f then
		inf.state = f
		sys.dispatch("DEV_CHG_STATUS_IND",getstate())
	end
end

sys.regmsg(rtos.MSG_PMD,proc)
init()
